<template>
  <div class="app-container">
    <div class="boader-container">
      <!-- 头部面包屑和按钮 -->
      <div class="option-bar">
        <el-breadcrumb style="margin-top: 10px" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>
            <i class="el-icon-sort-up"/>
            <label class="text-button" @click="rollbackTo(breadcrumbList.length-2)">返回上一级</label>
          </el-breadcrumb-item>
          <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.id">
            <span class="text-button" @click="rollbackTo(index)">{{ item }}</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
        <div>
          <el-button
            :disabled="cuStatus !== 0"
            size="small"
            icon="el-icon-folder-add"
            type="primary"
            plain
            @click="showAllFile"
            v-if="flagFile"
          >查看全部文件
          </el-button>
          <el-button
            :disabled="cuStatus !== 0"
            size="small"
            icon="el-icon-folder-add"
            type="primary"
            plain
            @click="showAllFold"
            v-else
          >查看文件夹
          </el-button>
          <el-button :disabled="cuStatus !== 0" size="small" icon="el-icon-folder-add" type="primary" plain
                     @click="addFold"
          >新建文件夹
          </el-button>
          <el-button :disabled="selections.length === 0 || cuStatus !== 0" size="small" icon="el-icon-delete"
                     type="primary" plain @click="toDelAll"
          >删除
          </el-button>

          <my-uploader :target="getCurrentPath()" @onSuccess="onSuccess"></my-uploader>
<!--          <my-uploader-fold :target="getCurrentPath()" @onSuccess="onSuccess"></my-uploader-fold>-->

          <!--          <el-button :disabled="cuStatus !== 0" size="small" icon="el-icon-download" type="primary" @click="toDownload" plain>下载</el-button>-->
        </div>
      </div>
      <!-- 文件展示列表 -->
      <el-table
        ref="table"
        size="medium"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="data"
        :highlight-current-row="true"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @current-change="handleCurrentChange"
        @row-dblclick="handleRowDblclick"
        @row-contextmenu="openMenu"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="fileName" label="文件名" width="300px" class="select_disable">
          <template slot-scope="props">
            <!--            <img :src="props.row.isFold? folder:image"-->
            <!--                 style="vertical-align:middle"-->
            <!--            >-->
            <i :class="props.row.isFold? 'el-icon-folder':'el-icon-picture'"></i>
            <span :ref="'text'+ props.row.id" style="padding: 0 10px;">{{ props.row.fileName }}</span>
            <!-- 文件名修改框 -->
            <div :ref="props.row.id" style="display: none">
              <el-input v-model="rename" style="display: inline-block;width: 200px;" size="small"/>
              <!-- 编辑按钮 -->
              <span class="tag-span" @click="comfirmRename">
                <i class="el-icon-check"></i>
              </span>
              <span class="tag-span" @click="cancelRename">
                <i class="el-icon-close"></i>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小"/>
        <el-table-column prop="creater" label="创建者"/>
        <el-table-column prop="time" label="创建时间"/>
      </el-table>
      <div style="padding: 20px;font-size: 14px">
        <span>全部 <el-tag type="info">{{ this.data.length }}</el-tag> 个, 已选择 <el-tag type="info"
        >{{ this.selections.length }}</el-tag> 个</span>
      </div>
    </div>
    <!-- 右键菜单 -->
<!--    <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">-->
<!--      <li @click="toRename">重命名</li>-->
<!--      <li @click="toDownload" v-if=" this.current !== null && !this.current.isFold">下载</li>-->
<!--      <li @click="toOpen" v-if=" this.current !== null && this.current.isFold">打开</li>-->
<!--      <li v-if="this.current.isFold" @click="toOpen">打开</li>-->
<!--      <li @click="toDel">删除</li>-->
<!--    -->
<!--    </ul>-->
  </div>
</template>
<script>
import myUploader from './component/myUploader'
import { mapGetters } from 'vuex'
import { getFileList, addFold, del, edit, delAll, download, getFileLists } from '@/api/file'
import myUploaderFold from '@/views/folder/component/myUploaderFold'
import { getFile } from '@/service/commonService'
import { getMousePosition } from '@/utils/index2'

export default {
  name: 'Uploadfolder',
  components: { myUploader, myUploaderFold },
  data() {
    return {
      upload: '/upload',
      current: null, selections: [], rename: null, breadcrumbList: ['首页'],
      visible: false,
      top: 0,
      left: 0,
      cuStatus: 0,  // 1:新建文件夹,
      data: [],
      flagFile: true,  // 是否只查看文件夹
      folder: './images/icon-folder.png',
      image: './images/icon-image.png'
    }
  },
  watch: {
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  computed: {
    ...mapGetters([
      'fileManagerApi'
    ])
  },
  mounted() {
    this.init()
  },
  methods: {
    getMousePosition,
    // 初始化文件列表
    init() {
      if(this.flagFile){
        this.flagFile = true
        const path = this.getCurrentPath()
        getFileList(path).then(res => {
          console.log(res.data)
          this.data = res.data
        })
      }else {
        this.flagFile = false
        const path = this.getCurrentPath()
        getFileLists(path).then(res => {
          console.log(res.data)
          this.data = res.data
        })
      }

    },
    handleSelectionChange(val) {
      this.selections = val
    },
    handleCurrentChange(val) {
      // 当前如果是属于添加新文件夹状态，这时候点击其他行代表取消新建
      // 这样做主要是为了防止文件名重复，没有其他更好办法
      if (this.cuStatus === 1) {
        this.data.splice(0, 1)
      }
      // 某行处于编辑状态，当点击其他行，编辑状态取消
      if (this.current !== null) {
        this.changeEditShow(false)
      }
      this.cuStatus = 0
      this.current = val
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(val)
    },
    handleRowDblclick(row, column, event) {
      if (row.isFold) {
        this.breadcrumbList.push(row.fileName)
        this.init()
      }
    },
    toOpen() {
      if (this.current.isFold) {
        this.breadcrumbList.push(this.current.fileName)
        this.init()
      }
    },
    comfirmRename() {
      if (this.checkExist()) {
        if (this.cuStatus === 1) {
          // 新增文件夹时，文件名框的提交为新增操作
          const params = {
            path: this.getCurrentPath(),
            name: this.rename
          }
          addFold(params).then(res => {
            this.init()
          })
        } else {
          // 重命名时的操作
          const params = {
            path: this.getCurrentPath(),
            newName: this.rename,
            oldName: this.current.fileName
          }
          edit(params).then(res => {
            this.init()
          })
          // this.current.fileName = this.rename
        }
        this.cuStatus = 0
        this.changeEditShow(false)
      }
    },
    cancelRename() {
      // 当前如果是属于添加新文件夹状态，点击取消框代表取消新建，这样做主要是为了防止文件名重复，没有其他更好办法
      if (this.cuStatus === 1) {
        this.$refs.table.clearSelection()
        this.data.splice(0, 1)
      } else {
        this.changeEditShow(false)
      }
      this.cuStatus = 0
      this.rename = null
    },
    changeEditShow(isEdit) {
      this.$refs[this.current.id].style.display = isEdit ? 'inline' : 'none'
      this.$refs['text' + this.current.id].style.display = isEdit ? 'none' : 'inline'
    },
    rollbackTo(index) {
      this.breadcrumbList = index >= 0 ? this.breadcrumbList.slice(0, index + 1) : this.breadcrumbList
      this.init()
    },
    onSuccess() {
      // this.$notify.success("上传成功")
      this.$nextTick(function() {
        this.init()
      })
    },
    onError(err) {
      this.$notify.error(err)
    },
    addFold() {
      // 暂时新增的data，只有在点击命名窗口的勾选项后才真正向后端发起新建文件夹请求
      // isFold 图标为文件夹形式
      const fold = { id: this.data.length, fileName: '新建文件夹', fileSize: '--', creater: '管理员', isFold: true, time: '' }
      this.data.splice(0, 0, fold)
      this.$refs.table.setCurrentRow(fold)
      this.$nextTick(function() {
        this.toRename()
        this.cuStatus = 1
      })
    },
    toDel() {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          path: this.getCurrentPath(),
          name: this.current.fileName
        }
        del(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!',
            duration: 2500
          })
          this.init()
        }).catch(() => {
          console.log('fdf')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 批量删除
    toDelAll() {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const fileNames = this.selections.map(sel => {
          return sel.fileName
        })
        const params = {
          path: this.getCurrentPath(),
          names: fileNames
        }
        delAll(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!',
            duration: 2500
          })
          this.init()
        }).catch(() => {
          console.log('fdf')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    toDownload() {
      const path = this.getCurrentPath()
      // const name = this.current.fileName
      const names = this.selections.map(sel => {
        return sel.fileName
      })
      names.forEach(name => {
        this.createDownload(path, name)
      })
    },
    createDownload(path, name) {
      const elink = document.createElement('a')
      elink.style.display = 'none'
      document.body.appendChild(elink)
      elink.href = this.fileManagerApi + '/file/download?path=' + path + '&name=' + name
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    },
    toRename() {
      this.rename = this.current.fileName
      this.changeEditShow(true)
      this.cuStatus = 2
    },
    openMenu(row, column, event) {
      // 右键同时触发选择，主要时为了将当前行设为current
      this.handleCurrentChange(row)
      event.preventDefault()
      // 根据文档相对位置来获得右击位置
      const result = this.getMousePosition(event)
      this.left = result.x
      this.top = result.y
      this.visible = true
    },
    closeMenu() {
      this.visible = false
    },
    checkExist() {
      return this.data.every(item => {
        if (item.fileName === this.rename && item.id !== this.current.id) {
          this.$message.error('同级中存在同名文件,文件名不能重复')
          return false
        }
        return true
      })
    },
    getCurrentPath() {
      // var folds = ['/home/fzuir/newspaper_data']
      var folds = []
      folds.push(process.env.VUE_APP_SELECT_PATH)
      // var folds = ['/home/data/newspaper/jpg']   // 本地区别
      this.breadcrumbList.slice(1).forEach(item => {
        folds.push(item)
      })
      console.log(folds.join('/'))
      return folds.join('/')

    },
    // 查看全部文件
    showAllFile() {
      this.flagFile = false
      this.init()
    },
    showAllFold() {
      this.flagFile = true
      this.init()
    },
    showPreview(source) {


      var file = source.files[0];
      console.log(source.files)
      if(window.FileReader) {
        var fr = new FileReader();
        fr.onloadend = function(e) {
          document.getElementById("portrait").src = e.target.result;
        };
        fr.readAsDataURL(file);
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px;

  .boader-container {
    border-radius: 10px;
    border: 1px dashed #ccc;
    padding: 10px;

    .option-bar {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }

    .tag-span {
      border: 2px solid #daebfe;
      text-align: center;
      color: #101010;
      background-color: #ebeef5;
      font-weight: 700;
      display: inline-block;
      width: 24px;
    }

    .text-button, .tag-span {
      cursor: pointer !important;
    }

    .row-operation {
      position: absolute;
      right: 40px;
      display: none;
      color: rgb(64, 158, 255);

      span {
        margin: 0px 5px;
        line-height: 2em;
      }
    }

    .select_disable {
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }

    .upload-demo {
      display: inline;
    }
  }
}

.table-head {
  color: gray;
}

.contextmenu {
  //height: 60px;
  margin: 50px 0 0 0 ;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 10px 0 0 0 ;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);

  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;

    &:hover {
      background: #eee;
    }
  }
}

.el-button + .el-button {
  margin-left: 0
}

</style>
